package com.ruoyi.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.domain.UserModule;
import com.ruoyi.admin.mapper.UserPaperMapper;
import com.ruoyi.admin.domain.UserAnswer;
import com.ruoyi.admin.domain.UserPaper;
import com.ruoyi.admin.model.request.CheckUserPaperReq;
import com.ruoyi.admin.model.response.PaperDetailResp;

import com.ruoyi.admin.model.response.UserPaperDetailResp;
import com.ruoyi.admin.service.PaperService;
import com.ruoyi.admin.service.QuestionAnswerService;
import com.ruoyi.admin.service.QuestionService;
import com.ruoyi.admin.service.UserAnswerService;
import com.ruoyi.admin.service.UserModuleService;
import com.ruoyi.admin.service.UserPaperService;
import com.ruoyi.api.model.response.AnswerHistoryResp;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * (UserPaper)表服务实现类
 *
 * @author zhoujun
 * @since 2023-04-11 14:19:11
 */
@Service("userPaperService")
public class UserPaperServiceImpl extends ServiceImpl<UserPaperMapper, UserPaper> implements UserPaperService {

    @Autowired
    private PaperService paperService;

    @Autowired
    private UserModuleService userModuleService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionAnswerService questionAnswerService;

    @Autowired
    private UserAnswerService userAnswerService;


    @Override
    public boolean submitPaper(Long userPaperId){
        UserPaper byId = Optional.ofNullable(this.getById(userPaperId)).orElseThrow(() ->
                new ServiceException(StringUtils.format("未找到该userPaperId数据 = {}", userPaperId))
        );
        byId.setUpdateBy(SecurityUtils.getUsername());
        byId.setUpdateTime(new Date());
        byId.setStatus(1);
        byId.setPaperEndTime(new Date());
        return this.updateById(byId);
    }

    @Override
    public UserPaperDetailResp userPaper(Long userPaperId){
        UserPaper byId = Optional.ofNullable(this.getById(userPaperId)).orElseThrow(() ->
                new ServiceException(StringUtils.format("未找到该userPaperId数据 = {}", userPaperId))
        );
        PaperDetailResp paperDetailResp = paperService.paperDetail(byId.getPaperId());
        List<UserModule> userModuleList = userModuleService.list(new LambdaQueryWrapper<UserModule>()
                .eq(UserModule::getUserPaperId, userPaperId)
        );

        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setPaperId(paperDetailResp.getPaperId());
        List<AnswerHistoryResp> answerHistoryResps = userAnswerService.answerHistory(userAnswer);

        // questionService.list(new LambdaQueryWrapper<>());

        UserPaperDetailResp userPaperDetailResp = new UserPaperDetailResp();
        userPaperDetailResp.setPaperId(paperDetailResp.getPaperId());
        userPaperDetailResp.setPaperName(paperDetailResp.getPaperName());
        userPaperDetailResp.setPaperType(paperDetailResp.getPaperType());
        userPaperDetailResp.setPaperStatus(paperDetailResp.getPaperStatus());
        userPaperDetailResp.setCountdown(paperDetailResp.getCountdown());
        userPaperDetailResp.setUserPaperId(userPaperId);
        userPaperDetailResp.setPaperScore(byId.getPaperScore());

        List<UserPaperDetailResp.ModuleDTO> moduleDTOList = paperDetailResp.getModuleList().stream().map(moduleDTO -> {
            UserPaperDetailResp.ModuleDTO moduleDTO1 = new UserPaperDetailResp.ModuleDTO();
            moduleDTO1.setPaperId(moduleDTO.getPaperId());
            moduleDTO1.setModuleType(moduleDTO.getModuleType());
            moduleDTO1.setModuleName(moduleDTO.getModuleName());

            userModuleList.stream().filter(userModule -> userModule.getModuleType().equals(moduleDTO.getModuleType()))
                    .findFirst().ifPresent(userModule -> {
                        moduleDTO1.setUserModuleId(userModule.getId());
                        moduleDTO1.setModuleScore(userModule.getModuleScore());
                    });

            List<UserPaperDetailResp.TopicDTO> topicDTOList = moduleDTO.getTopicList().stream().map(topicDTO -> {
                UserPaperDetailResp.TopicDTO topicDTO1 = new UserPaperDetailResp.TopicDTO();
                List<UserPaperDetailResp.UserQuestionInfoResp> userQuestionInfoResps = topicDTO.getQuestionList().stream().map(questionInfoResp -> {
                    UserPaperDetailResp.UserQuestionInfoResp userQuestionInfoResp = new UserPaperDetailResp.UserQuestionInfoResp();
                    userQuestionInfoResp.setQuestionId(questionInfoResp.getQuestionId());
                    userQuestionInfoResp.setQuestion(questionInfoResp.getQuestion());
                    userQuestionInfoResp.setQuestionType(questionInfoResp.getQuestionType());
                    userQuestionInfoResp.setOptionList(questionInfoResp.getOptionList());
                    userQuestionInfoResp.setAnswer(questionInfoResp.getAnswer());
                    userQuestionInfoResp.setMaterialUrl(questionInfoResp.getMaterialUrl());
                    userQuestionInfoResp.setMaterialType(questionInfoResp.getMaterialType());
                    userQuestionInfoResp.setMaterialContent(questionInfoResp.getMaterialContent());
                    userQuestionInfoResp.setTopicId(questionInfoResp.getTopicId());
                    String userAnswerStr = answerHistoryResps.stream().filter(f -> f.getQuestionId().equals(questionInfoResp.getQuestionId()))
                            .map(AnswerHistoryResp::getQuestionAnswer).findFirst().orElse("");
                    userQuestionInfoResp.setUserAnswer(userAnswerStr);
                    return userQuestionInfoResp;
                }).collect(Collectors.toList());
                topicDTO1.setQuestionList(userQuestionInfoResps);
                return topicDTO1;
            }).collect(Collectors.toList());
            moduleDTO1.setTopicList(topicDTOList);
            return moduleDTO1;
        }).collect(Collectors.toList());
        userPaperDetailResp.setModuleList(moduleDTOList);
        return userPaperDetailResp;
    }


    @Override
    public boolean checkUserPaper(CheckUserPaperReq checkUserPaperReq){
        List<UserModule> userModuleList = userModuleService.list(new LambdaQueryWrapper<UserModule>()
                .eq(UserModule::getUserPaperId, checkUserPaperReq.getUserPaperId())
        );
        List<UserModule> moduleList = userModuleList.stream().map(userModule -> {
            CheckUserPaperReq.ModuleScore moduleScore = checkUserPaperReq.getModuleScoreScoreList().stream().filter(f -> f.getModuleId().equals(userModule.getId()))
                    .findFirst().get();
            userModule.setModuleScore(moduleScore.getModuleScore());
            return userModule;
        }).collect(Collectors.toList());
        userModuleService.updateBatchById(moduleList);
        int paperScore = (moduleList.stream().mapToInt(UserModule::getModuleScore).sum() / moduleList.size());
        UserPaper userPaper = this.getById(checkUserPaperReq.getUserPaperId());
        userPaper.setPaperScore(paperScore);
        return this.updateById(userPaper);
    }
}

